<?php
class Plugins_AjaxPlugin extends Zend_Controller_Plugin_Abstract
{
	public function routeStartup(Zend_Controller_Request_Abstract $request){
		if($request->isXmlHttpRequest())
		{
			$layout = Zend_Layout::getMvcInstance();
			$layout->disableLayout();
		}
			
	}


	public function postDispatch(Zend_Controller_Request_Abstract $request)
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		$viewRenderer->initView();
		$view = $viewRenderer->view;

		if($request->isXmlHttpRequest() && ($request->getControllerName() != "ajax"))
		{
				
			$layout = Zend_Layout::getMvcInstance();
			$layout->disableLayout();
			$this->getResponse()->clearAllHeaders();
			$this->getResponse()->setHeader('content-type', 'application/json', true);
			$this->getResponse()->clearBody();
				
			if(!isset($view->out))
			{
				$out = array();
				foreach($request->getParam('adr') as $key => $options)
				{
					$out[$key] =  $view->{$key}->xml;
				}
			}else{
				$this->getResponse()->setBody(json_encode($view->out));
			}

		}
	}

}